package dom4j.book;

import dom4j.TestA_DOM4J;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.ArrayList;
import java.util.List;

public class Test_Books2 {

    public static void main(String[] args) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(TestA_DOM4J.class.getClassLoader().getResourceAsStream("books.xml"));
        Element root = document.getRootElement();
        List<Element> bookElements = root.elements("book");
        List<Book> books = new ArrayList<>();
        for (Element bookElem : bookElements){
            Book book = new Book();
            books.add(book);
            String category = bookElem.attributeValue("category");
            book.setCategory(category);
            String cover = bookElem.attributeValue("cover");
            book.setCover(cover);
            String title = bookElem.elementText("title");
            String lang = bookElem.element("title").attributeValue("lang");
//            BookTitle bookTitle = new BookTitle();
//            bookTitle.setContent(title);
//            bookTitle.setLang(lang);
//            book.setTitle(bookTitle);
            book.addTitle(title,lang);
            List<Element> authorElements = bookElem.elements("author");
            for (Element authorElem : authorElements){
                book.addAuthor(authorElem.getText());
            }
            String year = bookElem.elementText("year");
            book.setYear(Integer.parseInt(year));
            String price = bookElem.elementText("price");
            book.setPrice(Double.parseDouble(price));
        }
        for(Book book:books){
            System.out.println(book);
        }
    }
}
